package org.cleverframe.modules.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.cleverframe.common.controller.BaseController;
import org.cleverframe.common.persistence.tree.BuildTreeUtil;
import org.cleverframe.common.persistence.tree.ITreeNode;
import org.cleverframe.common.vo.AjaxMessage;
import org.cleverframe.modules.sys.SysBeanNames;
import org.cleverframe.modules.sys.SysJspUrlPath;
import org.cleverframe.modules.sys.entity.Dict;
import org.cleverframe.modules.sys.entity.Organization;
import org.cleverframe.modules.sys.service.OrganizationService;
import org.cleverframe.webui.easyui.data.ComboBoxJson;
import org.cleverframe.webui.easyui.data.DataGridJson;
import org.cleverframe.webui.easyui.data.TreeGridNodeJson;
import org.cleverframe.webui.easyui.data.TreeNodeJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 组织机构Controller<br>
 * @author LiZW
 * @version 2015年6月26日 下午4:28:02
 */
@Controller
@RequestMapping("/${mvcPath}/sys")
@Transactional(readOnly = true)
public class OrganizationController extends BaseController
{
    @Autowired
    @Qualifier(SysBeanNames.OrganizationService)
    private OrganizationService organizationService;
    
    /**
     * 跳转到机构管理页面<br>
     */
    @RequestMapping("/getSysOrganizationJsp")
    public ModelAndView getSysOrganizationJsp(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView(SysJspUrlPath.SysOrganization);
        return mav;
    }
    
    /**
     * 获取所有机构信息<br>
     * @return 返回EasyUI TreeGrid控件格式数据
     * */
    @ResponseBody
    @RequestMapping("/getAllOrganization")
    public DataGridJson<TreeGridNodeJson<Organization>> getAllOrganization(HttpServletRequest request, HttpServletResponse response)
    {
        DataGridJson<TreeGridNodeJson<Organization>> treeGrid = new DataGridJson<TreeGridNodeJson<Organization>>();
        List<Organization> orgList = organizationService.findAllOrganization();
        for (Organization org : orgList)
        {
            TreeGridNodeJson<Organization> node = new TreeGridNodeJson<Organization>(org.getParentId(), org);
            treeGrid.addRow(node);
        }
        return treeGrid;
    }
    
    /**
     * 获取所有机构信息，排除当前机构以及当前机构的所有下级机构<br>
     * @return 返回EasyUI Tree控件格式数据
     */
    @ResponseBody
    @RequestMapping("/getOrgTreeExcludeOneself")
    public List<ITreeNode> getOrgTreeExcludeOneself(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @RequestParam(value = "fullPath", required = false, defaultValue = "XXX") String fullPath)
    {
        fullPath = fullPath + "%";
        List<Organization> orgList = organizationService.getOrgTreeExcludeOneself(fullPath);
        List<ITreeNode> nodes = new ArrayList<ITreeNode>();
        for (Organization org : orgList)
        {
            TreeNodeJson node = new TreeNodeJson(org.getParentId(), org.getId(), org.getFullPath(), org.getName(), "", false, "open");
            nodes.add(node);
        }
        return BuildTreeUtil.bulidTree(nodes);
    }
    
    /**
     * 查询机构的直接子机构的可选类型<br>
     * @return
     */
    @ResponseBody
    @RequestMapping("/getChildOrgType")
    public List<ComboBoxJson> getChildOrgType(
            HttpServletRequest request, 
            HttpServletResponse response,
            @RequestParam(value = "orgId", required = true) Long orgId)
    {
        List<ComboBoxJson> comboBoxList = new ArrayList<ComboBoxJson>();
        List<Dict> dictList = organizationService.getChildOrgType(orgId);
        for (Dict dict : dictList)
        {
            ComboBoxJson comboBox = new ComboBoxJson(false, dict.getDictKey(), dict.getDictValue());
            comboBoxList.add(comboBox);
        }
        return comboBoxList;
    }
    
    /**
     * 增加机构<br>
     */
    @ResponseBody
    @RequestMapping("/addOrganization")
    @Transactional(readOnly = false)
    public AjaxMessage addOrganization(
            HttpServletRequest request, 
            HttpServletResponse response,
            @Valid Organization org,
            BindingResult bindingResult)
    {
        AjaxMessage message=new AjaxMessage();
        if(beanValidator(bindingResult, message))
        {
            if(organizationService.addOrganization(org, message))
            {
                message.setMessage("机构数据保存成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 更新机构<br>
     */
    @ResponseBody
    @RequestMapping("/updateOrganization")
    @Transactional(readOnly = false)
    public AjaxMessage updateOrganization(
            HttpServletRequest request, 
            HttpServletResponse response,
            @Valid Organization org,
            BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage();
        if (beanValidator(bindingResult, message))
        {
            if (organizationService.updateOrganization(org, message))
            {
                message.setMessage("机构数据更新成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 删除机构<br>
     */
    @ResponseBody
    @RequestMapping("/deleteOrg")
    @Transactional(readOnly = false)
    public AjaxMessage deleteOrg(
            HttpServletRequest request, 
            HttpServletResponse response,
            @Valid Organization org,
            BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage();
        if (beanValidator(bindingResult, message))
        {
            if (organizationService.deleteOrg(org, message))
            {
                message.setMessage("机构数据删除成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 获取组织架构中的所有公司<br>
     * @return EasyUI ComboBox数据绑定的Json格式数据
     */
    @ResponseBody
    @RequestMapping("/getAllCompany")
    public List<ComboBoxJson> getAllCompany(HttpServletRequest request, HttpServletResponse response)
    {
        List<ComboBoxJson> comboBoxList = new ArrayList<ComboBoxJson>();
        List<Organization> list = organizationService.getAllCompany();
        for (Organization org : list)
        {
            ComboBoxJson comboBox = new ComboBoxJson(false, org.getName(), org.getId().toString());
            comboBoxList.add(comboBox);
        }
        return comboBoxList;
    }
    
    /**
     * 获取某公司的所有机构(包括该公司)<br>
     * @param companyId 公司ID
     * @return 返回EasyUI Tree控件格式数据
     */
    @ResponseBody
    @RequestMapping("/getOrgByCompany")
    public List<ITreeNode> getOrgByCompany(
            HttpServletRequest request, 
            HttpServletResponse response,
            @RequestParam(value="companyId" ,required=true) Long companyId)
    {
        List<Organization> orgList= organizationService.getOrgByCompany(companyId);
        List<ITreeNode> nodes = new ArrayList<ITreeNode>();
        for (Organization org : orgList)
        {
            TreeNodeJson node = new TreeNodeJson(org.getParentId(), org.getId(), org.getFullPath(), org.getName(), "", false, "open");
            nodes.add(node);
        }
        return BuildTreeUtil.bulidTree(nodes);
    }
    
    /**
     * 获取当前公司的所有机构数据
     * @return 返回EasyUI Tree控件格式数据
     */
    @ResponseBody
    @RequestMapping("/findCurrentCompanyOrg")
    public List<ITreeNode> findCurrentCompanyOrg(HttpServletRequest request, HttpServletResponse response)
    {
        // 查询当前公司所有的机构
        List<Organization> oegList = organizationService.getOrgByCompany(userUtils.getCurrentCompanyId());
        List<ITreeNode> nodes = new ArrayList<ITreeNode>();
        for (Organization org : oegList)
        {
            TreeNodeJson node = new TreeNodeJson(org.getParentId(), org.getId(), org.getFullPath(), org.getName(), "", false, "open");
            node.setObject(org);
            nodes.add(node);
        }
        return BuildTreeUtil.bulidTree(nodes);
    }
}
